<hr>
<p>title: 278.First Bad Version<br>date: 2021-10-18 15:25:34<br>tags:</p>
<pre><code>- LeeCode
</code></pre><p>categories: </p>
<pre><code>- LeeCode
</code></pre><p>hidden: true</p>
<h2 id="cateHidden-false"><a href="#cateHidden-false" class="headerlink" title="cateHidden: false"></a>cateHidden: false</h2><h3 id="描述"><a href="#描述" class="headerlink" title="描述"></a>描述</h3><blockquote>
<p>You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.</p>
<p>Suppose you have n versions [1, 2, …, n] and you want to find out the first bad one, which causes all the following ones to be bad.</p>
<p>You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.</p>
</blockquote>
<h3 id="测试用例"><a href="#测试用例" class="headerlink" title="测试用例"></a>测试用例</h3><pre><code class="lang-bash">Input: n = 5, bad = 4
Output: 4
Explanation:
call isBadVersion(3) -&gt; false
call isBadVersion(5) -&gt; true
call isBadVersion(4) -&gt; true
Then 4 is the first bad version.
</code></pre>
<h3 id="题解"><a href="#题解" class="headerlink" title="题解"></a>题解</h3><p>二分法。</p>
<pre><code class="lang-js">var solution = function(isBadVersion) {
    /**
     * @param {integer} n Total versions
     * @return {integer} The first bad version
     */
    return function(n) {
        // 二分法
        let left = 1, right = n;
        while (left &lt; right) {
            let mid = Math.floor((left + right) / 2);
            if(isBadVersion(mid)) right = mid;
            else left = mid + 1;
        }
        return left;
    };
};
</code></pre>
<h3 id="结果"><a href="#结果" class="headerlink" title="结果"></a>结果</h3><blockquote>
<p>Accepted</p>
<p>22/22 cases passed (105 ms)</p>
<p>Your runtime beats 28.07 % of javascript submissions</p>
<p>Your memory usage beats 64.6 % of javascript submissions (38.5 MB)</p>
</blockquote>
